package com.letukeji.web.riverdelictmanagement.controller.user;

import com.github.pagehelper.Page;
import com.letukeji.web.riverdelictmanagement.bean.ApiResult;
import com.letukeji.web.riverdelictmanagement.bean.SearchObj;
import com.letukeji.web.riverdelictmanagement.bean.User;
import com.letukeji.web.riverdelictmanagement.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.naming.directory.SearchControls;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (User)表控制层
 *
 * @author figol
 * @since 2019-10-22 13:13:10
 */
@Controller
@RequestMapping("user")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;

    @RequestMapping("")
    public String toIndex(HttpServletRequest request) {
        return "user/index";
    }

    @RequestMapping("dashboard")
    public String dashboard(HttpServletRequest request) {
        return "user/dashboard";
    }

    @RequestMapping("list")
    public String list(HttpServletRequest request, Model model) {
        return "user/list";
    }

    @RequestMapping("add")
    public String add(HttpServletRequest request, Model model) {
        return "user/add";
    }


    @ResponseBody
    @RequestMapping("search")
    public Object search(HttpServletRequest request) { // 通过@Validated进行字段校验
        SearchObj searchObj = this.fn_GenerateSearch(request);
        List<User> list =  userService.find(searchObj);
        Map<String, Object> result = new HashMap<>();
        result.put("data",list);
        result.put("code",0);
        result.put("count",userService.findTotal(searchObj));
        result.put("msg","");
        return result;
    }

    public SearchObj fn_GenerateSearch(HttpServletRequest request) {
        String where = this.fn_GenerateWhereClause(request);
        int curPage = this.fn_GetPageNum(request);
        int pageSize = this.fn_GetPageSize(request);
        int offset = (curPage-1)*pageSize;
        String orderBy = this.fn_GenerateOrderBy(request);
        return new SearchObj(where,orderBy,offset,pageSize);
    }

    public String fn_GenerateWhereClause(HttpServletRequest request) {
        List<String> where = new ArrayList<String>();
        String field = request.getParameter("field");
        String value = request.getParameter("value");
        if (value != null && value != "") {
            where.add(field + " like '%" + value + "%'");
        }
        if(where.size()==0){
            where.add("1=1");
        }
        return String.join(" and ", where);
    }

    public int fn_GetPageNum(HttpServletRequest request){
        if (request.getParameter("page") != null
                && request.getParameter("page").equals("")==false) {
            return Integer.parseInt(request.getParameter("page"));
        }
        return 1;
    }

    public int fn_GetPageSize(HttpServletRequest request){
        if (request.getParameter("limit") != null
                && request.getParameter("limit").equals("")==false) {
            return Integer.parseInt(request.getParameter("limit"));
        }
        return SearchObj.defaultPageSize;
    }

    public String fn_GenerateOrderBy(HttpServletRequest request) {
        //String order = "id desc";
        String order = "id desc";
        return order;
    }









    /**
     * 用户注册接口
     * @param user 注册的用户对象
     * @return 注册的用户
     */
    @ResponseBody
    @RequestMapping("register")
    public ApiResult doRegister(@Validated User user) { // 通过@Validated进行字段校验
        user.setUsername(user.getUsername().trim());
        User u = userService.insert(user);
        return u == null ? ApiResult.fail("注册失败, 用户名已被使用") : ApiResult.success(user);
    }

    /**
     * 根据用户id更新用户信息的接口
     * @param user 更新的用户对象, 不为null的属性为要更新的
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("update")
    public ApiResult updateUser(@Validated User user, HttpServletRequest request) {
        User u = (User) request.getSession().getAttribute("user");
        user.setId(u.getId());
        User update = userService.update(user);
        return update != null ? ApiResult.success(update) : ApiResult.fail("更新失败");
    }

    /**
     * 更新密码接口
     * @param password 新密码
     * @param oldPassword 旧密码
     * @param request 用以获取用户id
     * @return
     */
    @ResponseBody
    @PostMapping("update/password")
    public ApiResult updatePassword(String password, String oldPassword, HttpServletRequest request) {
        if (password == null || password.length() > 20 || password.length() < 6)
            return ApiResult.fail("更新失败, 密码长度为6-20为位");
        User user = (User) request.getSession().getAttribute("user");
        if (user.getPassword().equals(oldPassword)) {
            User u = new User();
            u.setPassword(password);
            u.setId(user.getId());
            user = userService.update(u);
            request.getSession().setAttribute("user", user);
            return ApiResult.success("更新密码成功");
        }
        return ApiResult.fail("原密码不正确");
    }

}